// pages/index/index.js
import req from "../../utils/req";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUseGetUserProfile: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    showModal: false,
    username: "",
    password: "",
    userInfo: wx.getStorageSync('userInfo'),
    hasUserInfo: wx.getStorageSync('userInfo'),
  },
   goToAbout: function() {
    wx.navigateTo({
      url: '/pages/about/about'
    })
  },

  showInput: function() {
    this.setData({
      showModal: true,
    });
  },
  goToMine: function() {
    wx.navigateTo({
      url:  '/pages/mine/mine',
    })
  },
  login: async function(loginToken) {
    console.log('loginToken', loginToken)
    let res = await req("/login", loginToken, "POST");

    if(res.code === 1) {
      wx.showToast({
        title: '登录失败',
        icon: "error",
        duration: 2000
      });
    }

    if(res.code === 0) {
      wx.setStorage({
        data: res.data,
        key: 'cookie',
      })

      wx.setStorage({
        data: loginToken,
        key: 'loginToken'
      })
      wx.showToast({
        title: '登录成功',
        duration: 500,
        success: () => {
         setTimeout(()=> {
          wx.redirectTo({
            url: '/pages/workIndex/workIndex',
          })
         }, 1000)
        },
      })
    }
  },
  reLogin: function() {
    let token = wx.getStorageSync('loginToken')
    if (!token) {
      // 没有账号密码的情况
      this.showInput()
    } else {
      // 重新登陆，刷新cookie
      console.log("退出登录", wx.getStorageSync('cookie'))
      req(`/logout`)
      this.login(token)
    }
  },

  complete: function() {
    let {username, password} = this.data;
    let loginToken = {
      username: username,
      passwd: password
    }
    this.login(loginToken)
  },
  bindGetUserInfo (e) {
    console.log(e.detail.userInfo)
  },
  getUserProfile(e) {


    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        // console.log(res.userInfo)
        wx.setStorageSync('userInfo', res.userInfo)
        this.setData({
          showModal: true,
        });
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }

    // 每次先用cache的cookie退出登录，
    // let cookie = wx.getStorageSync('cookie');
    // let userInfo = wx.getStorageSync('userInfo');

    // console.log(userInfo, cookie)
    // if (cookie) {
    //   console.log('尝试重新登录')
    //   console.log(cookie)
    //   req(`/logout`)
    //   // 重新登陆，刷新cookie
    //   this.login(wx.getStorageSync('loginToken'))
    // }

    

   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onShow: function () {
    let userInfo = wx.getStorageSync('userInfo')
    // console.log('onShow', userInfo)

    this.setData({
      hasUserInfo: userInfo ? true:false,
      userInfo: userInfo
    })
  },


})